package xdu.ble.user.service;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xdu.ble.common.enums.ExceptionCode;
import xdu.ble.common.exception.BLEException;
import xdu.ble.user.entity.Admin;
import xdu.ble.user.mapper.AdminMapper;
import xdu.ble.user.utils.CodecUtils;

import java.util.Date;

/**
 * @Author com.alibaba.lizhen
 * @Date 2021/1/14 4:01 下午
 * @Version 1.0
 * @Description
 */
@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;


    private final Logger logger = LoggerFactory.getLogger(AdminService.class);


    /**
     * 登录，根据手机号和密码查询
     *
     * @return Result
     */
    public Admin login(String phoneNum, String passWord) {
        Admin admin = new Admin();
        admin.setPhoneNum(phoneNum);
        //1 查询是否存在
        admin = this.adminMapper.selectOne(admin);
        if (admin == null) {
            throw new BLEException(ExceptionCode.ADMIN_NOT_REGISTER);
        }
        //2 校验密码，根据密码和盐解密
        if (!StringUtils.equals(admin.getPassWord(), CodecUtils.md5Hex(passWord, admin.getSalt()))) {
            throw new BLEException(ExceptionCode.PHONE_OR_PASSWORD_ERROR);
        }
        //3 重新更新最新登陆时间
        admin.setLatestLoginTime(new Date());
        if (adminMapper.updateByPrimaryKey(admin) != 1) {
            logger.error("更新出错" + admin);
            throw new BLEException(ExceptionCode.DB_UPDATE_ERROR);
        }
        //否则返回正确结果
        return admin;
    }

}
